<?php

namespace App\Services\Pay\Order;

use App\Core\Traits\Numeral;
use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Game\Pay\Order\Transfer as Order;

class TransferService extends Service
{
    use DatabaseMysql, Numeral;

    /**
     * 获取数据列表
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]
     */
    public function getList($request)
    {
        $query = Order::query();

        // 筛选【平台】
        $this->makeWhereParamOrg($request, $query);
        // 筛选【时间】
        // $this->makeWhereParamDatetime($request, $query);
	    $this->makeWhereParamDatetimeTimeZone1($request, $query, 'created',  'datetime', '' ,'' , 'hour');
	    // 筛选【搜索】
        $this->makeWhereParamSearch($request, $query);
        // 筛选【币种】
        $this->makeWhereParam($request, 'currency', $query);
        // 筛选【状态】
        $this->makeWhereParam($request, 'status', $query);
        // 筛选【类型】
        $this->makeWhereParam($request, 'transfer_type', $query);
        // 数据条数
        $total = (clone $query)->count();
        // 统计数据
        $stats = $this->getStats(clone $query);
        // 排序分页
        $this->makeOrderParam($request, $query)->makePaginationParam($request, $query);
        // 查询数据
        $collection = $query->with('org:code,name')->get();

        return [
            $collection,
            $total,
            $stats
        ];
    }

    /**
     * 获取统计信息
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return array
     */
    private function getStats($query)
    {
        // USD【合计】
        $usd = (clone $query)->getQuery()
            ->selectRaw("IFNULL(CAST(SUM(usd->'$.amount') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS amount")
            ->first();

        // 分币种【合计】
        $sts = $query->selectRaw('currency,SUM(amount) as amount')->groupBy('currency')->get();

        return [
            'usd' => $usd['amount'],
            'sts' => $sts,
        ];
    }
}
